﻿using System;
using System.Web.Services.Protocols;
using System.Xml.XPath;
using System.Globalization;

using Microsoft.Crm.SdkTypeProxy;


namespace CSP.CRM.ISVExtensions
{
  public partial class ProcedureDetailPage : System.Web.UI.Page
  {
    protected CspInfo csp;
    protected bool disabled;
    protected int procedureTypeCode = -1, languageCode = 1033;
    protected Guid incidentId = Guid.Empty, procedureId = Guid.Empty;
    protected string organizationName;
    protected string procedureUrl;
    protected CrmService crm;
    protected IXPathNavigable incidentDom;

    protected void Page_Load(object sender, EventArgs e)
    {
      try
      {
        Initialize();
        if (disabled)
          btOpenProcedure.Enabled = false;
        else
          ShowProcedureDetailLink();
      }
      catch (SoapException soapEx)
      {
        Response.Write(soapEx.Detail.OuterXml);
      }
    }

    protected void ShowProcedureDetailLink()
    {
      if (procedureId != Guid.Empty) // View procedure detail
        procedureUrl = String.Format(CultureInfo.InvariantCulture, "/userdefined/edit.aspx?etc={0}&id={1}", procedureTypeCode, procedureId);
      else if (incidentId != Guid.Empty) // Look up detail information
      {
        incidentDom = csp.FetchIncidentAndContactXml(incidentId);
        FetchHelper r = new FetchHelper(incidentDom);
        procedureId = r.GetGuid("csp_procedureid");
        if (procedureId != Guid.Empty) // Procedure exists
          procedureUrl = String.Format(CultureInfo.InvariantCulture, "/userdefined/edit.aspx?etc={0}&id={1}", procedureTypeCode, procedureId);
        else // Procedure not yet created
          procedureUrl = BuildNewProcedureUrl();
      }
      btOpenProcedure.OnClientClick = 
        String.Format(CultureInfo.InvariantCulture, "window.open('{0}', 'wProcedure', 'resizable=true,scrollbar=false,toolbar=false,status=1,width=833,height=565');", procedureUrl);
    }


    // Read arguments from query string and create helper objects
    protected void Initialize()
    {     
      if (Request["procId"] != null)
        procedureId = new Guid(Request["procid"]);
      if (Request["id"] != null)
        incidentId = new Guid(Request["id"]);
      if (Request["proctype"] != null)
        procedureTypeCode = Int32.Parse(Request["proctype"], CultureInfo.InvariantCulture);
      if (Request["orgname"] != null)
        organizationName = Request["orgname"];
      if (Request["userlcid"] != null)
        languageCode = Int32.Parse(Request["userlcid"], CultureInfo.InvariantCulture);

      // DASB 19/01/2009 Problemas cuando se accede utilizando prefijo de host
      //System.Net.IPHostEntry ipEntries = System.Net.Dns.GetHostEntry(Request.Url.Host);
      //string strServerIp = ipEntries.AddressList[0].ToString();
      //string crmServerUrl = String.Format(CultureInfo.InvariantCulture, "{0}://{1}:{2}", Request.Url.Scheme, strServerIp, Request.Url.Port);


      string crmServerUrl = String.Format(CultureInfo.InvariantCulture, "{0}://{1}:{2}", Request.Url.Scheme, Request.Url.Host, Request.Url.Port);
      csp = new CspInfo(new Uri(crmServerUrl), organizationName, languageCode);
      btOpenProcedure.Text = csp.GetConfigText("ProcedureDetailLinkText");

      if ((incidentId == Guid.Empty) || (procedureTypeCode == -1))
      {
        disabled = true;
        return;
      }      
    }

    private string BuildNewProcedureUrl()
    {
      FetchHelper r = new FetchHelper(incidentDom);
      string ticketNumber = r.GetText("ticketnumber");
      string title = r.GetText("title");
      string fullName = r.GetText("customerid.fullname");
      string address = r.GetText("customerid.address1_line1");
      string city = r.GetText("customerid.address1_city");
      string postalCode = r.GetText("customerid.address1_postalcode");
      string emailAddress = r.GetText("customerid.emailaddress1");
      string telephone = r.GetText("customerid.telephone1");
      string contactId = r.GetText("customerid");

      string url = "/userdefined/edit.aspx?etc=" + procedureTypeCode;
      url += String.Format(CultureInfo.InvariantCulture, "&csp_incidentid={0}&csp_incidentidname={1}", incidentId, ticketNumber);
      url += String.Format(CultureInfo.InvariantCulture, "&csp_contactid={0}&csp_contactidname={1}", contactId, fullName);
      url += String.Format(CultureInfo.InvariantCulture, "&csp_title={0}", title);
      if (address != null)
        url += String.Format(CultureInfo.InvariantCulture, "&csp_address={0}", address);
      if (city != null)
        url += String.Format(CultureInfo.InvariantCulture, "&csp_city={0}", city);
      if (postalCode != null)
        url += String.Format(CultureInfo.InvariantCulture, "&csp_postalcode={0}", postalCode);
      if (emailAddress != null)
        url += String.Format(CultureInfo.InvariantCulture, "&csp_emailaddress={0}", emailAddress);
      if (telephone != null)
        url += String.Format(CultureInfo.InvariantCulture, "&csp_phone={0}", telephone);
      return url;
    }

  }
}
